package com.hengfoxwolf.definerecyclerviewlayoutmanagerdemo
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

/**
 *@desc BaseRvAdapter
 *@author liuliheng
 *@time 2022/12/22  15:06
 **/
abstract class BaseRvAdapter<T, B : ViewDataBinding>(
    private val dataSet: MutableList<T>
) : RecyclerView.Adapter<BaseRvAdapter<T, B>.ViewHolder>() {

    protected var mContext: Context? = null

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        lateinit var binding: B
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        if (mContext == null) {
            mContext = parent.context
        }
        val binding: B =
            DataBindingUtil.inflate(LayoutInflater.from(mContext), getLayoutId(), parent, false)
        val holder = ViewHolder(binding.root)
        holder.binding = binding
        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.executePendingBindings()
        bindData(holder, dataSet[position], position)
    }

    override fun getItemCount(): Int = dataSet.size

    abstract fun getLayoutId(): Int

    abstract fun bindData(holder: ViewHolder, dataItem: T, position: Int)
}